package com.monkeyboy.first.stopthreads;

/**
 * 描述：     注意Thread.interrupted()方法的目标对象是“当前线程”，而不管本方法来自于哪个对象
 */
public class RightWayInterrupted {

    public static void main(String[] args) throws InterruptedException {

        Thread threadOne = new Thread(() -> {
            try {
                while(true){
                    System.out.println("6: "+Thread.currentThread().isInterrupted());
                    /**
                     * Thread.interrupted()是让当前线程恢复中断，也就是如果线程被中断了调用这个方法后就会恢复从而不会中断
                     * 测试：取消注释和加注释查看控制台，注释之后程序会停止运行并相应中断抛出异常，如果打开注释就会清除中断，然后程序
                     * 就会一直运行
                     */
//                        System.out.println("--"+Thread.interrupted());
                    Thread.sleep(500);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            //try catch之后会清除中断的标识，所以下面又恢复了false状态
            System.out.println("7 "+Thread.currentThread().isInterrupted());
        });

        // 启动线程
        threadOne.start();
        //设置中断标志
        threadOne.interrupt();
        //获取中断标志
        System.out.println("1 " + threadOne.isInterrupted());
        System.out.println("1 " + threadOne.isInterrupted());
        //获取中断标志并重置，只能当前线程执行，所以这里执行没有作用，不能清除中断的状态
        System.out.println("2 " + threadOne.interrupted());
        //获取中断标志并重置
        System.out.println("3 " + Thread.interrupted());
        //获取中断标志
        System.out.println("4 " + threadOne.isInterrupted());
        threadOne.join();
        System.out.println("5 "+threadOne.isInterrupted());
        System.out.println("Main thread is over.");
    }
}
